package com.zzty.zzlp.serviceimpl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.zzty.zzlp.dao.ClassGroupMapper;
import com.zzty.zzlp.dao.SelfExamTransationMapper;
import com.zzty.zzlp.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zzty.zzlp.entity.SelfExamTransation;
import com.zzty.zzlp.entity.User;
import com.zzty.zzlp.service.SelfExamTransationService;

@Service
public class SelfExamTransationServiceImpl implements SelfExamTransationService {

    @Autowired
    SelfExamTransationMapper selfExamTransationMapper;

    @Autowired
    ClassGroupMapper cgd;

    @Autowired
    UserDao userDao;

    public void updateIsValid(int examId, int userId, int totalTime) {
        if (totalTime <= 120) {
            selfExamTransationMapper.updateIsValid(examId, userId, 1);
        } else {
            selfExamTransationMapper.updateIsValid(examId, userId, 0);
        }

    }

    public void updateAnswers(int examId, int userId, String answers) {
        selfExamTransationMapper.updateAnswers(examId, userId, answers);

    }

    public String searchStartTime(int examId, int userId) {
        Date now = new Date();
        if (selfExamTransationMapper.searchSETByExamIdAndUserId(examId, userId).getStartTime() == null) {
            SimpleDateFormat myFmt = new SimpleDateFormat("HH:mm:ss");
            String startTime = myFmt.format(now);
            updateStartTime(examId, userId, startTime);
            // 把HH:mm:ss变为yyyy-MM-dd HH:mm:ss格式
            String time[] = startTime.split(":");
            SimpleDateFormat myFmt1 = new SimpleDateFormat("yyyy-MM-dd");
            String time1 = myFmt1.format(now);// 获取当前日期
            time1 = time1 + " " + time[0] + ":" + time[1] + ":" + time[2];
            return time1;
        } else {
            String db_time = selfExamTransationMapper.searchSETByExamIdAndUserId(examId, userId).getStartTime();
            String time[] = db_time.split(":");
            SimpleDateFormat myFmt1 = new SimpleDateFormat("yyyy-MM-dd");
            String time1 = myFmt1.format(now);// 获取当前日期
            time1 = time1 + " " + time[0] + ":" + time[1] + ":" + time[2];
            return time1;
        }
    }

    public void updateStartTime(int examId, int userId, String startTime) {
        selfExamTransationMapper.updateStartTime(examId, userId, startTime);

    }

    public void updateTotalTime(int examId, int userId, int min) {
        selfExamTransationMapper.updateTotalTime(examId, userId, min);

    }

    public boolean isTotalTimeExist;

    public Integer searchTotalTime(int examId, int userId) {
        System.out.println("totalTime:" + selfExamTransationMapper.searchSETByExamIdAndUserId(examId, userId).getTotalTime());
        if (selfExamTransationMapper.searchSETByExamIdAndUserId(examId, userId).getTotalTime() == null) {

            isTotalTimeExist = false;
            String startTime = selfExamTransationMapper.searchSETByExamIdAndUserId(examId, userId).getStartTime();

            String time[] = startTime.split(":");
            SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd");
            Date now = new Date();// now为作业提交时间
            String time1 = myFmt.format(now);// 获取当前日期
            time1 = time1 + " " + time[0] + ":" + time[1] + ":" + time[2];// 将数据库中的时间加上日期
            // 变为"yyyy-MM-dd
            // HH:mm:ss"格式的字符串
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = sdf.parse(time1);// 将字符串转化为日期类
                long s = now.getTime() - date.getTime();
                long min = s / 1000 / 60;
                updateTotalTime(examId, userId, (int) min);
                updateIsValid(examId, userId, (int) min);

            } catch (ParseException e) {
                e.printStackTrace();
            }
            return null;
        } else {
            isTotalTimeExist = true;
            return selfExamTransationMapper.searchSETByExamIdAndUserId(examId, userId).getTotalTime();
        }
    }

    public boolean getIsTotalTimeExist() {
        return isTotalTimeExist;
    }

    public String searchAnswerPath(int examId, int userId) {

        if (selfExamTransationMapper.searchSETByExamIdAndUserId(examId, userId) == null) {
            return null;

        }
        return selfExamTransationMapper.searchSETByExamIdAndUserId(examId, userId).getAnswers();
    }

    public String searchAnswer(int examId, int userId) {

        String answerPath = selfExamTransationMapper.searchSETByExamIdAndUserId(examId, userId).getAnswers();
        String answer = "";
        // System.out.println(examId);
        // System.out.println(userId);
        // System.out.println(answerPath);
        if ((answerPath == null) || ("".equals(answerPath))) {
            answer = "无";
            return answer;
        } else {
            try {
                // String encoding = "utf-8";
                File file = new File(answerPath);
                if (file.isFile() && file.exists()) { // 判断文件是否存在
                    InputStreamReader read = new InputStreamReader(new FileInputStream(file), "GB2312");// 考虑到编码格式
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt = null;
                    while ((lineTxt = bufferedReader.readLine()) != null) {
                        // System.out.println(lineTxt);
                        answer += lineTxt + "\r\n";
                    }
                    read.close();
                    return answer;
                } else {
                    System.out.println("找不到指定的文件");
                }
            } catch (Exception e) {
                System.out.println("读取文件内容出错");
                e.printStackTrace();
            }
            return answer;
        }

    }

    public Integer searchIsValid(int examId, int userId) {

        if (selfExamTransationMapper.searchSETByExamIdAndUserId(examId, userId) == null) {

            return null;
        }
        Integer valid = selfExamTransationMapper.searchSETByExamIdAndUserId(examId, userId).getIsValid();

        return valid;
    }

    public void updateScore(int examid, int userid, String score) {
        selfExamTransationMapper.updateScore(examid, userid, score);

    }

    public void updateComment(int examid, int userid, String comment) {
        selfExamTransationMapper.updateComment(examid, userid, comment);

    }

    public List<Integer> searchStuidByTeaName(String name) {

        return null;
    }

    public String searchScore(int examId, int userId) {
        if (selfExamTransationMapper.searchSETByExamIdAndUserId(examId, userId) == null) {

            return null;
        }
        return selfExamTransationMapper.searchSETByExamIdAndUserId(examId, userId).getScore();
    }

    public Integer searchTotalTimeById(int examId, int userId) {
        if (selfExamTransationMapper.searchSETByExamIdAndUserId(examId, userId) == null) {
            return null;
        }
        return selfExamTransationMapper.searchSETByExamIdAndUserId(examId, userId).getTotalTime();
    }

    public void addSelfExamTransation(SelfExamTransation set) {
        selfExamTransationMapper.addSelfExamTransation(set);

    }

    public void updateRank(int examId) {
        selfExamTransationMapper.updateRank(examId);

    }

    public Integer searchWinnerId(int examId) {
        return selfExamTransationMapper.searchWinnerId(examId);
    }

    public Map<String, String> searchIdAndScore(int examId) {
        List<SelfExamTransation> list = selfExamTransationMapper.searchSETByExamId(examId);

        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < list.size(); i++) {

            map.put(list.get(i).getUserId() + "", list.get(i).getScore());
            // map.put(rs.getString("Userid"), rs.getString("Score"));

        }
        return map;
    }

    public String getWinnerId(Map<String, String> map) {
        for (Map.Entry<String, String> temp : map.entrySet()) {
            if ("A".equals(temp.getValue())) {
                return temp.getKey();
            }

        }
        return null;
    }

    public String getLastOne(Map<String, String> map) {
        String result = null;
        for (Map.Entry<String, String> temp : map.entrySet()) {
            if ("D".equals(temp.getValue())) {
                result = temp.getKey();
                break;
            }

        }

        if (result == null) {
            for (Map.Entry<String, String> temp : map.entrySet()) {
                if ("C".equals(temp.getValue())) {
                    result = temp.getKey();
                    break;
                }

            }

        }
        if (result == null) {
            for (Map.Entry<String, String> temp : map.entrySet()) {
                if ("B".equals(temp.getValue())) {
                    result = temp.getKey();
                    break;
                }

            }

        }
        return result;

    }

    public ArrayList<String> generateGroup(Map<String, String> map, int classid) {

        ArrayList<String> groups = new ArrayList<String>();
        Set<String> ids = map.keySet();
        String group;
        String winnerId = getWinnerId(map);
        if (map.size() % 2 > 0) {
            ids.remove(winnerId);
            Object[] leftIds = ids.toArray();
            groups.add(winnerId);
            if (!groups.isEmpty()) {
                for (int i = 0; i < leftIds.length; i = i + 2) {
                    String tmp = leftIds[i] + "|" + leftIds[i + 1];
                    groups.add(tmp);
                }
            }
        } else {

            String lastOne = getLastOne(map);
            groups.add(winnerId + "|" + lastOne);
            ids.remove(winnerId);
            ids.remove(lastOne);
            Object[] leftIds = ids.toArray();
            for (int i = 0; i < leftIds.length; i = i + 2) {
                String tmp = leftIds[i] + "|" + leftIds[i + 1];
                groups.add(tmp);

            }
        }
        // 将group插入数据库
        // TODO
        // List<Integer> clazzGroups = cgd.getIdByClassId(classid);
        // for (int i = 0; i < clazzGroups.size(); i++) {
        // cgd.updateClassGroup(clazzGroups.get(i), groups.get(i));
        // }
        return groups;
    }

    public List<String> userMailAddresses(List<Integer> userids) throws Exception {
        List<String> userEmailAddresses = new ArrayList<String>();

        for (int i = 0; i < userids.size(); i++) {
            User user = userDao.selectUserById(userids.get(i));
            // User user = ud.findAllByID(userids.get(i));
            String userEmailAddress = user.getEmail();
            userEmailAddresses.add(userEmailAddress);
        }
        return userEmailAddresses;
    }

    public String searchComment(Integer examId, Integer userId) {
        return selfExamTransationMapper.searchComment(examId, userId);
    }

    @Override
    public List<SelfExamTransation> searchSETByExamId(Integer examId) {

        return selfExamTransationMapper.searchSETByExamId(examId);
    }

}
